#!/opt/anaconda3/bin/python
"""
Filename: badminton-ordering.py 
Created on Tue Sep  1 10:49:18 CST 2020

@author: Kefeng Zhu (zhukefeng@inspur.com, zkf1985@gmail.com, zkf85@163.com)

Description:

"""
from playsound import playsound 
import datetime
from selenium import webdriver
#from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
import sys
import os
import time
import logging

import smtplib
from email.mime.text import MIMEText
from email.header import Header

log_save_dir = './'
# Setup Logging
# create a logger
logger = logging.getLogger("KFZ")
logger.setLevel(level=logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
# set file handler
handler = logging.FileHandler(os.path.join(log_save_dir, 'log.txt'))
handler.setFormatter(formatter)
logger.addHandler(handler)
# set stream handler
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)
start_time = datetime.datetime.strptime(str(datetime.datetime.now().date())+'8:00', '%Y-%m-%d%H:%M')
end_time = datetime.datetime.strptime(str(datetime.datetime.now().date())+'20:00', '%Y-%m-%d%H:%M')

daylist = []
for i,dday in enumerate(sys.argv):
    if i == 0:
        continue
   
    if dday not in '01234567':
        raise ValueError(f'{dday} is not right')
    
    daylist.append(int(dday))


def run(is_send_email=True):
    #chrome_driver_dir = '/home/zhukf/inspur_login/'
    chrome_driver_dir = './'
    chromedriver = os.path.join(chrome_driver_dir, 'chromedriver')

    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('window-size=414x736')
    options.add_argument('log-level=3')
    browser = webdriver.Chrome(executable_path=chromedriver, options=options)
    #browser = webdriver.Chrome(executable_path=chromedriver)
    #wait = WebDriverWait(browser, 10)
    #print('[kf info] init done')
    logger.info("="*40)
    logger.info("Chrome initialization done!")

    browser.get('https://h5.yingheying.com/alauda/?#/reservePlace/34319/0?placeId=75210')
    time.sleep(3)
    #print('[kf info] get done')
    logger.info("Webpage loading done!")

    choose_name = browser.find_element_by_class_name('show-name.sel')
    #choose_name = browser.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div[1]/div[1]/span[1]')
    choose_name.click()
    time.sleep(1)
    badminton_name = browser.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div[1]/div[2]/div/div[2]')
    badminton_name.click()
    time.sleep(3)

    # 选择时间
    date_list=[
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[2]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[3]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[4]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[5]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[6]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[7]',
        '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[1]/div[8]'
    ]

    available_list = []

    # added by KF on Sun Sep 27 15:37:36 CST 2020
    #--------------------------------------------------------------------------------
    # 特殊日期（跳过）
    exempt_date_list = [
            '10月1日', 
            '10月2日', 
            '10月3日', 
            '10月4日', 
            '10月5日', 
            '10月6日', 
            '10月7日', 
            '10月8日', 
            ]

    #--------------------------------------------------------------------------------
    week_dict = {0:'今天',1:'周一',2:'周二',3:'周三',4:'周四',5:'周五',6:'周六',7:'周日'}
    valid_date_list = ['周二'] if len(daylist) == 0 else [week_dict[i] for i in daylist]

    if week_dict[datetime.datetime.now().isoweekday()] in valid_date_list and '今天' not in valid_date_list:
        valid_date_list.append('今天')
    
    logger.info('需要爬取的日期列表为:'+' '.join(valid_date_list))
    for date in date_list:
        #if browser.find_element_by_xpath(date+'/span[1]').text in ['周六', '周日']:
        #    continue
        # 只看周日
        #if not browser.find_element_by_xpath(date+'/span[1]').text in ['周六','周日']:
        if not browser.find_element_by_xpath(date+'/span[1]').text in valid_date_list:
            continue
        # 特殊日期跳过
        if browser.find_element_by_xpath(date+'/span[2]').text in exempt_date_list:
            logger.info('[kf info] %s 为豁免（跳过）日期，不看！！' % browser.find_element_by_xpath(date+'/span[2]').text)

            continue

        browser.find_element_by_xpath(date).click()
        time.sleep(2)
        #browser.find_element_by_xpath(date).click()
        time.sleep(10)
        
        preValid = False
        curValid = False
        # 场地 9:00 - 20:00点场地
        if(browser.find_element_by_xpath(date+'/span[1]').text in ['周六','周日']):
            stime,etime=9,20
            #stime,etime=18,20
        else:
            stime,etime=18,20
        logger.info(f"[羽球场地信息] 日期：{browser.find_element_by_xpath(date+'/span[1]').text}:{browser.find_element_by_xpath(date+'/span[2]').text} {stime}:00 - {etime}:00")
        for i in range(stime,etime):
            for court_num in range(1, 21):
                time_list = '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[3]/div[1]/div[2]/div/div[%d]/div[%d]' % (court_num, i-6)
                if browser.find_element_by_xpath(time_list).get_attribute('class') == 'order-btn':
                    #print("Cur time %d, and court_num : %d is order-btn"%(i,court_num))
                    curValid = True 
                else:
                    #print("Cur time %d, and court_num : %d is not order-btn"%(i,court_num))
                    curValid = False
                #print("for time: %d, for yardNum: %d, preValid:%s,curValid:%s"%(i,court_num,str(preValid),str(curValid)))
                tmp = '//*[@id="app"]/div/div[1]/div[2]/div[2]/div[2]/div[3]/div[1]/div[2]/div/div[%d]/div[1]' % (court_num)
                
                if curValid:
                    break
            
            if preValid and curValid:
                available_list.append([
                        browser.find_element_by_xpath(date+'/span[1]').text + browser.find_element_by_xpath(date+'/span[2]').text,
                        i,
                        court_num])
                    
                logger.info(f'\t场地{court_num} {start_time}:00 - {end_time}:00')
                #print('\t\t18:00: ', '有场' if browser.find_element_by_xpath(pm18).get_attribute('class') == 'order-btn' else '无场')
                logger.info('\t\t%d:00: %s' % (i, '有场' if browser.find_element_by_xpath(time_list).get_attribute('class') == 'order-btn' else '无场'))      
            preValid = curValid


    # 发邮件
    email_sent = False
    if is_send_email:
        if not len(available_list):
            #print('[kf info] 无可定场地！不需要发邮件！')
            logger.info('[kf info] 无可定场地！不需要发邮件！')

        else:
            #print('[kf info] 有场地！！需要发邮件提醒！', available_list)
            #logger.info('[kf info] 有场地！！需要发邮件提醒！', available_list)
            logger.info('[kf info] 有场地！！需要发邮件提醒！')
            content = ''
            for slot in available_list:
                #print(slot)
                #content += "时间：%s - 场地：%d\n" % (slot[0], slot[1])
                content += "时间：%s - , 时段：%02d:00，场地：%d\n" % (slot[0], slot[1], slot[2])

            subject = "【ARDPBG羽球场地预定】有场地了！"
            sender = "uihsvi@126.com"        #发送方
            password = "jimwo59"
            
            recver = ["uihsvi@qq.com","uihsvi@126.com"]
            #recver = "zhukefeng@inspur.com,tongpeilin@inspur.com" #接收方

            content += "订场链接：\n"
            content += "https://h5.yingheying.com/alauda/?#/reservePlace/34319/0?placeId=75210"

            message = MIMEText(content,"plain","utf-8")
            #content 发送内容     "plain"文本格式   utf-8 编码格式
             
            message['Subject'] = subject #邮件标题
            message['To'] = ','.join(recver) #收件人
            message['From'] = sender #发件人
             
            #print('[kf info] 发送邮件至%s ...' % recver)
            logger.info('[kf info] 发送邮件至%s ...' % recver)
            try:
                smtp = smtplib.SMTP_SSL("smtp.126.com",994) #实例化smtp服务器
                smtp.login(sender,password)                 #发件人登录
                smtp.sendmail(sender,recver,message.as_string()) #as_string 对message的消息进行了封装
                smtp.close()
                #print("发送成功！！")
                logger.info("发送成功！！")
                email_sent = True
             
            except smtplib.SMTPException:
                #print("Error: 无法发送邮件")
                logger.info("Error: 无法发送邮件")
            now_time = datetime.datetime.now()
            if now_time > start_time and now_time < end_time:
                playsound('0801.mp3')
    logger.info("")
    return email_sent


if __name__ == "__main__":
    run()
